import 'dart:convert';

import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/manager/login_manager.dart';
import 'package:tender_flutter/manager/permission_manager.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/helper/badge_manager.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/goods/goods_page.dart';
import 'package:tender_flutter/page/home/home_page.dart';
import 'package:tender_flutter/page/person/person_page.dart';
import 'package:tender_flutter/page/subscription/subscription_page.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/click.dart';
import 'package:tender_flutter/utils/jpush_utils.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/sputils.dart';

import 'supplier/supplier_page.dart';
import 'track/track_page.dart';

ValueNotifier<int> badgeNumNotifier = ValueNotifier(0);

class MainHomePage extends StatefulWidget {
  MainHomePage({Key key}) : super(key: key);

  @override
  _MainHomePageState createState() => _MainHomePageState();
}

class _MainHomePageState extends State<MainHomePage> {
  var _pageController = PageController();
  int _selectedIndex = 0;
  GlobalKey<ConvexAppBarState> tabBarKey = GlobalKey<ConvexAppBarState>();

  List<TabItem> getTabs(BuildContext context) => [
        TabItem(
            icon: Image.asset("assets/images/icon_tab_home_normal.png"),
            activeIcon: Image.asset("assets/images/icon_tab_home_select.png"),
            title: '首页'),
        TabItem(
            icon: Image.asset("assets/images/icon_tab_subscription_normal.png"),
            activeIcon:
                Image.asset("assets/images/icon_tab_subscription_select.png"),
            title: '订阅'),
        TabItem(
            icon: Image.asset("assets/images/icon_tab_supplier.png"),
            activeIcon: Image.asset("assets/images/icon_tab_supplier.png"),
            title: '供应商'),
        DataManager.instance.isAppstore
            ? TabItem(
                icon: Image.asset("assets/images/icon_tab_track_normal.png"),
                activeIcon:
                    Image.asset("assets/images/icon_tab_track_select.png"),
                title: '商城')
            : TabItem(
                icon: Image.asset("assets/images/icon_tab_track_normal.png"),
                activeIcon:
                    Image.asset("assets/images/icon_tab_track_select.png"),
                title: '追踪'),
        TabItem(
            icon: Image.asset("assets/images/icon_tab_person_normal.png"),
            activeIcon: Image.asset("assets/images/icon_tab_person_select.png"),
            title: '我的'),
      ];

  List<Widget> pages = [
    TabHomePage(),
    TabSubscriptionPage(),
    TabSupplierPage(),
    DataManager.instance.isAppstore ? TabGoodsPage() : TabTrackPage(),
    TabPersonPage(),
  ];

  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();

    /// 页面渲染完成之后的回调，只执行一次
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      if (SPUtils.isLogined()) {
        BadgeManager.instance.updateSubscriptionNum();
      }
    });
    _initJpushEvent();
    Future.delayed(Duration(milliseconds: 8000), () {
      _checkAppVersionUpdate();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /*屏幕适配初始化*/
    ScreenAdapter.init(context);

    return WillPopScope(
        child: Scaffold(
            key: _scaffoldKey,
            body: PageView.builder(
              itemBuilder: (context, index) => pages[index],
              itemCount: pages.length,
              controller: _pageController,
              physics: NeverScrollableScrollPhysics(),
              onPageChanged: (index) {
                _jumpPage(index);
              },
            ),
            bottomNavigationBar: StyleProvider(
                style: Style(),
                child: ValueListenableBuilder(
                  valueListenable: badgeNumNotifier,
                  builder: (BuildContext ctx, int value, Widget child) {
                    return ConvexAppBar.badge(
                        value == 0
                            ? null
                            : {1: '${value > 999 ? "999+" : value}'},
                        badgeMargin: EdgeInsets.only(left: 20, bottom: 30),
                        key: tabBarKey,
                        items: getTabs(context),
                        height: 49,
                        top: -15,
                        curveSize: 80,
                        style: TabStyle.fixed,
                        elevation: 0.7,
                        backgroundColor: ThemeColors.colorWhite,
                        color: ThemeColors.colorType1,
                        activeColor: ThemeColors.colorType6,
                        initialActiveIndex: _selectedIndex, onTap: (index) {
                      _jumpPage(index);
                    });
                  },
                ))),
        //监听导航栏返回,类似onKeyEvent
        onWillPop: () =>
            ClickUtils.exitBy2Click(status: _scaffoldKey.currentState));
  }

  Future<void> _jumpPage(int index) async {
    if (index == 1 || index == 3 || index == 4) {
      var result = PermissionManager.isLogin();

      /// 没登录状态
      if (!result) {
        tabBarKey.currentState.animateTo(_selectedIndex);
        await LoginManager.login();
        return;
      }
    }
    setState(() {
      _selectedIndex = index;
    });
    _pageController.jumpToPage(index);
  }

  /// 初始化极光推送接受事件
  void _initJpushEvent() {
    JPushUtils.addJpushEventHanlder(
        onMyReceiveMessage: (Map<String, dynamic> message) async {
      print("消息推送-1-$message");
    }, onMyOpenNotification: (Map<String, dynamic> message) async {
      print("消息推送-2-$message");
      print("消息推送-2-1-${message["extras"]["cn.jpush.android.EXTRA"]}");
      Map<String, dynamic> msg =
          jsonDecode(message["extras"]["cn.jpush.android.EXTRA"]);
      if (msg.containsKey("sub_id")) {
        /// 订阅标讯
        String id = msg["sub_id"];
        LRouter.navigatorCtx(context).push(Routes.subscriptionListPage,
            arguments: SubscriptionListPageArguments(
                subscriptionId: int.parse(id), keywords: null));
      } else if (msg.containsKey("id")) {
        /// 标讯详情
        String id = msg["id"];
        LRouter.navigatorCtx(context)
            .push(Routes.tenderDetailPage, queryParams: {"tenderId": id});
      }
    }, onMyReceiveNotification: (Map<String, dynamic> message) async {
      print("消息推送-3-$message");
    }, onMyReceiveNotificationAuthorization:
            (Map<String, dynamic> message) async {
      print("消息推送-4-$message");
    }, onMyPlatformVersionFailure: (String message) async {
      print("消息推送-5-$message");
    }, onMyReceiveRegIdMessage: (String regId) async {
      //关联极光推送RegId
      ApiCommon.registerRegId(regId: regId);
      print("消息推送-注册id--$regId");
    });
  }

  /// app版本更新
  void _checkAppVersionUpdate() {
    String url = ApiPath.baseApi + ApiPath.app_update;
    FlutterXUpdate.checkUpdate(url: url, widthRatio: 0.7, isCustomParse: true);
  }
}

class Style extends StyleHook {
  /*中间Icon的图片*/
  @override
  double get activeIconSize => 40;

  @override
  double get iconSize => 25;

  @override
  double get activeIconMargin => 10;

  @override
  TextStyle textStyle(Color color) {
    return TextStyle(fontSize: ScreenAdapter.sp(26), color: color);
  }
}
